#include <stdlib.h>
#include <string.h>
#include <iostream.h>
#include "Record.h"



Type Schema :: FindType (int i) {

    if( i >= numAtts ) {
        cerr << " wrong index for schema\n";
        exit(0);
    }

    return myAtts[i].myType;
}

int Schema :: Find (char *attName) {

    for (int i = 0; i < numAtts; i++) {
        if (!strcmp (attName, myAtts[i].name)) {
            return i;
        }
    }

    // if we made it here, the attribute was not found
    return -1;
}

Schema :: Schema (char *fName, char *relName) {

    FILE *foo = fopen (fName, "r");

    // this is enough space to hold any tokens
    char space[200];

    fscanf (foo, "%s", space);
    int totscans = 1;

    // see if the file starts with the correct keyword
    if (strcmp (space, "BEGIN")) {
        cerr << "Unfortunately, this does not seem to be a schema file.\n";
        exit (1);
    }

    while (1) {

        // check to see if this is the one we want
        fscanf (foo, "%s", space);
        totscans++;
        if (strcmp (space, relName)) {

            // it is not, so suck up everything to past the BEGIN
            while (1) {

                // suck up another token
                if (fscanf (foo, "%s", space) == EOF) {
                    cerr << "Could not find the schema for the specified relation.\n";
                    exit (1);
                }

                totscans++;
                if (!strcmp (space, "BEGIN")) {
                    break;
                }
            }

            // otherwise, got the correct file!!
        } else {
            break;
        }
    }

    // count the number of attributes specified
    numAtts = 0;
    while (1) {
        fscanf (foo, "%s", space);
        if (!strcmp (space, "END")) {
            break;
        } else {
            fscanf (foo, "%s", space);
            numAtts++;
        }
    }

    // now actually load up the schema
    fclose (foo);
    foo = fopen (fName, "r");

    // go past any un-needed info
    for (int i = 0; i < totscans; i++) {
        fscanf (foo, "%s", space);
    }

    // and load up the schema
    myAtts = new AttSchema[numAtts];
    for (int i = 0; i < numAtts; i++ ) {

        // read in the attribute name
        fscanf (foo, "%s", space);
        myAtts[i].name = strdup (space);

        // read in the attribute type
        fscanf (foo, "%s", space);
        if (!strcmp (space, "Int")) {
            myAtts[i].myType = Int;
        } else if (!strcmp (space, "Double")) {
            myAtts[i].myType = Double;
        } else if (!strcmp (space, "String")) {
            myAtts[i].myType = String;
        } else {
            cout << "Bad attribute type for " << myAtts[i].name << "\n";
            exit (1);
        }
    }

    fclose (foo);
}


Schema :: ~Schema () {

    delete [] myAtts;
    myAtts = 0;
}

